import { useSelector } from 'react-redux'
import { Navigate, useLocation } from 'react-router-dom'
import { Suspense } from 'react'
import Loading from '@/pages/Loading'
import type { Token } from '@/types/login'
type AuthRouteProps = {
  children: JSX.Element
}
// 路由导航守卫
export default function AuthRoute({ children }: AuthRouteProps) {
  // 从redux中获取token数据
  const tokenInfo = useSelector((state: { login: Token }) => state.login)
  const location = useLocation()
  // 判断有没有token
  if (!tokenInfo.token) {
    // 记录当前路由地址，方便登录成功后回调回来
    const redirectUrl = location.pathname + location.search
    // 使用编程式导航的思想来进行规避，在当前组件中只能加载一个组件的要求(纯组件)
    return <Navigate to="/login" state={redirectUrl}></Navigate>
  }
  return <Suspense fallback={<Loading></Loading>}>{children}</Suspense>
}
